<template>
  <div>
    <!-- 触发按钮（对应流程图"用户选择更换手机"） -->
    <el-button type="primary" @click="openDialog">
      更换绑定手机
    </el-button>

    <!-- 弹窗（包含流程图所有交互步骤） -->
    <el-dialog
        v-model="dialogVisible"
        title="更换绑定手机"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          label-position="top"
      >
        <!-- 输入新手机号（对应流程图"输入新手机号"） -->
        <el-form-item label="新手机号" prop="phone">
          <el-input
              v-model="form.phone"
              placeholder="请输入新手机号"
              clearable
          />
        </el-form-item>

        <!-- 验证码部分（对应流程图"发送验证码"和"用户输入验证码"） -->
        <el-form-item label="短信验证码" prop="code">
          <div class="code-input">
            <el-input
                v-model="form.code"
                placeholder="请输入6位验证码"
                maxlength="6"
            />
            <el-button
                :disabled="!isPhoneValid || countdown > 0"
                @click="sendVerificationCode"
            >
              {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <!-- 提交按钮（对应流程图"提交更换请求"） -->
        <el-button
            type="primary"
            :loading="submitting"
            @click="submitForm"
        >
          确认更换
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import {ElMessage, ElNotification} from 'element-plus'
import { useUserStore } from '@/stores/userStore'

const useStore = useUserStore();
// 表单数据
const form = reactive({
  phone: '',
  code: ''
})

// 弹窗控制
const dialogVisible = ref(false)
const formRef = ref(null)
const submitting = ref(false)
const countdown = ref(0)

// 手机号验证规则
const isPhoneValid = computed(() => /^1[3-9]\d{9}$/.test(form.phone))

// 表单验证规则
const rules = reactive({
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码必须是6位数字', trigger: 'blur' }
  ]
})

// 打开弹窗（流程图第一步）
const openDialog = () => {
  dialogVisible.value = true
}

// 发送验证码（流程图"发送短信验证码到新手机"）
const sendVerificationCode = async () => {
  try {
    await useStore.getSsmCode(form.phone);
    startCountdown()
    simulateSmsNotification();
  } catch (error) {
    ElMessage.error('验证码发送失败')
  }
}

// 模拟短信通知（仅开发环境）
const simulateSmsNotification = () => {
    // 延迟几秒后显示验证码（模拟短信接收时间）
    setTimeout(() => {
      let code = '';
        code = useStore.ssmcode;
        console.log('ssmcode=', useStore.ssmcode)
      ElNotification({
        title: '短信验证码',
        message: `您收到的验证码是: ${code} (此功能仅在开发环境显示)`,
        type: 'info',
        duration: 0, // 不自动关闭
      });
    }, 2000); // 2秒后显示，模拟短信接收时间
}


// 60秒倒计时
const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 提交表单（流程图"提交更换请求"）
const submitForm = async () => {
  submitting.value = true
  try {
    await formRef.value.validate()

    await useStore.updatePhone({
      phone: form.phone,
      code: form.code
    })

    // 模拟流程图中的分支判断
    if (Math.random() > 0.3) { // 模拟70%成功率
      ElMessage.success('手机号更换成功') // 对应流程图"返回更换成功"
      dialogVisible.value = false
    } else {
      // 模拟流程图中的错误分支
      if (Math.random() > 0.5) {
        ElMessage.error('验证码错误') // 对应流程图"返回验证码错误"
      } else {
        ElMessage.error('手机号已被使用') // 对应流程图"返回手机号已被使用"
      }
    }
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.code-input {
  display: flex;
  gap: 10px;
}

.code-input :deep(.el-input) {
  flex: 1;
}
</style>